import logging
import autosub
import time

from httplib import HTTPSConnection
from urllib import urlencode

log = logging.getLogger('thelogger')

def _send_notify(message):
    try:
        http_handler = HTTPSConnection("boxcar.io")
        # change #####XXXXXXX###### to the AutoSub Service key of Boxcar.
        http_handler.request("POST", "/devices/providers/#####XXXXXXX######/notifications", headers = {'Content-type': "application/x-www-form-urlencoded"}, body = urlencode(message))
        response = http_handler.getresponse()
        request_status = response.status
    except:
        log.error("Boxcar: Failed to connect to Boxcar")
        return False
    if request_status == 200:
        log.info('Boxcar: Notification sent')
        return True
    else:
        log.error("Boxcar: Failed to sent notification")
        return False

def test_notify():
    message = 'Testing Boxcar! Seems to work!'
    
    data = {'email': autosub.BOXCARMAIL,
            'notification[from_screen_name]': 'AutoSub',
            'notification[message]': 'Test Message',
            'notification[from_remote_service_id]': int(time.time())}
    return _send_notify(data)
    
def send_notify(lang, subtitlefile, videofile):
    message = 'Auto-Sub just download %s' % subtitlefile
    
    data = {'email': autosub.BOXCARMAIL,
            'notification[from_screen_name]': 'AutoSub',
            'notification[message]': message.encode("utf-8"),
            'notification[from_remote_service_id]': int(time.time())}
    return _send_notify(data)
